package com.example.editor

import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import com.bear.richtext.RichText
import com.bear.richtext.type.*
import com.bear.richtext.utils.*
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import com.zhihu.matisse.internal.entity.CaptureStrategy
import org.json.JSONObject
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream

class FirstActivity : AppCompatActivity() {
    private var richContent: RichText? = null
    private val REQUEST_CODE_CHOOSE = 0x10 // 图库选取图片标识请求码


    private val tag_btn by lazy<Button> {
        findViewById(R.id.rich_tag)
    }

    private val img_btn by lazy<Button> {
        findViewById(R.id.rich_local_img)
    }

    private val save_btn by lazy<Button> {
        findViewById(R.id.rich_save)
    }

    private val canEdit by lazy<Button> {
        findViewById(R.id.rich_edit)
    }

    private val cannotEdit by lazy<Button> {
        findViewById(R.id.rich_no_edit)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_new)
        richContent = findViewById(R.id.richcontent)

        img_btn.setOnClickListener {
           openGallery()
        }

        tag_btn.setOnClickListener {
            richContent!!.insertTag("设置","#FF0000")
        }

        save_btn.setOnClickListener {
            val jsonArray = richContent!!.save()
            Log.i("测试",jsonArray.toString())
        }

        canEdit.setOnClickListener {
            richContent!!.setEditable(true)
        }

        cannotEdit.setOnClickListener {
            richContent!!.setEditable(false)
        }

//        val json1 = array<JSONObject>(
//            Text {
//                ItemText.CONTENT to "标题"
//                ItemText.TEXT_SIZE to 25
//                ItemText.TEXT_BOLD to true
//            },
//            Tag {
//                ItemTag.CONTENT to "测试标签"
//                ItemTag.BACKGROUND to "#FF0000"
//            },
//        )

        val json = array<JSONObject>(
            Text {
                ItemText.CONTENT to "标题"
                ItemText.TEXT_SIZE to 25
                ItemText.TEXT_BOLD to true
            },
            NewLine {
                ItemNewLine.ROWS to 0
            },
            Text {
                ItemText.CONTENT to "这是一段测试文本文本这是一段测试文本，这是一段测试文本，这是一段测试文本，这是一段测试文本是一段测试文本，这是一段测试文本，这是一段测试文本。"
            },
            NewLine {
                ItemNewLine.ROWS to 0
            },
            Tag {
                ItemTag.CONTENT to "测试标签"
                ItemTag.BACKGROUND to "#FF0000"
            },
            NewLine {
                ItemNewLine.ROWS to 0
            },
            Text {
                ItemText.CONTENT to "这是一段文本"
            },
            Text {
                ItemText.CONTENT to "hello world!!!"
            },
//            Gif {
//                ItemGif.GIF_PATH to "https://5b0988e595225.cdn.sohucs.com/images/20200504/cc14d246006e47d68da57176b16c41cc.gif"
//            },
            Clickable {
                ItemClickable.TEXT to "点击跳转"
                ItemClickable.URL to "http://www.baidu.com"
            },
            Image {
                ItemImage.IMAGE_PATH to "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fblog%2F202106%2F13%2F20210613235426_7a793.thumb.1000_0.jpeg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1678960220&t=4d6ea8e9289d95f9b8a4077f67c40104"
            }
        )

        richContent?.parse(json)
    }

    private fun openGallery() {
        Matisse.from(this).choose(MimeType.ofAll()).countable(true).maxSelectable(3)
            .gridExpectedSize(360).restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
            .thumbnailScale(0.85f).theme(R.style.Matisse_Zhihu).captureStrategy(
                CaptureStrategy(true, "com.sendtion.matisse.fileprovider")
            ).forResult(REQUEST_CODE_CHOOSE)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE_CHOOSE && data != null) {
            val mselected = Matisse.obtainResult(data)
            mselected.forEach {
                val imagePath = getFilePathFromUri(this,it)
                richContent?.insertImg(imagePath!!)
            }
        }
    }

    fun getFilePathFromUri(context: Context, uri: Uri): String? {
        if (uri == null) {
            return null
        }
        val resolver = context.contentResolver
        var inputStream: FileInputStream? = null
        var outputStream: FileOutputStream? = null
        try {
            val pfd = resolver.openFileDescriptor(uri, "r")
            pfd?.let {
                val fd = pfd.fileDescriptor
                inputStream = FileInputStream(fd)
                val outputFile = File.createTempFile("image", "tmp", context.cacheDir)
                val tempFilename = outputFile.absolutePath
                outputStream = FileOutputStream(tempFilename)

                var read = 0
                var bytes = ByteArray(2048)
                while (true) {
                    read = inputStream!!.read(bytes)
                    if (read == -1) {
                        break
                    } else {
                        outputStream!!.write(bytes, 0, read)
                    }
                }
                return File(tempFilename).absolutePath
            }
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            inputStream?.close()
            outputStream?.close()
        }
        return null
    }
}